package prototype;

import java.io.*;

/**
 * @program: javase
 * @description:
 * @author: luolidong
 * @create: 2021-06-12 21:00
 * @version: 1.0
 */
public class User implements Serializable,Cloneable {
    private int id;
    private String name;
    private int[] friends;
    private User wife;

    @Override
    protected Object clone() throws CloneNotSupportedException {
//        User user = null;
//        try {
//            user=(User) super.clone();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return user;
        return super.clone();
    }

    public User clone2(){
        //        使用反序列化方式
        ByteArrayInputStream bis=null;
        ObjectInputStream ois=null;
        ByteArrayOutputStream bos=null;
        ObjectOutputStream oos=null;
        try {
//            先序列化读取
            bos=new ByteArrayOutputStream();
            oos=new ObjectOutputStream(bos);
            oos.writeObject(this);

//            再写入
            bis=new ByteArrayInputStream(bos.toByteArray());
            ois=new ObjectInputStream(bis);
            User user = (User) ois.readObject();
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public User() {
    }

    public User(int id, String name, int[] friends, User wife) {
        this.id = id;
        this.name = name;
        this.friends = friends;
        this.wife = wife;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int[] getFriends() {
        return friends;
    }

    public void setFriends(int[] friends) {
        this.friends = friends;
    }

    public User getWife() {
        return wife;
    }

    public void setWife(User wife) {
        this.wife = wife;
    }
}
